extends TextureRect

@export var data: IngredientData #记得在编辑器里给每个实例拖入不同的.tres
#获取主场景的文本框来显示说明
@onready var info_label = %InfoPanel.get_child(0)
@onready var timer: Timer = $Timer
var sfx_take = preload("res://sound/bar/basewine_take.wav")

func _ready():
	#初始化外观
	if data:
		texture = data.icon
		expand_mode = TextureRect.EXPAND_IGNORE_SIZE

	#连接鼠标信号
	mouse_entered.connect(_on_mouse_entered_start_timer)
	mouse_exited.connect(_on_mouse_exited_reset)
	
	timer.timeout.connect(_on_timer_timeout_show)


#鼠标移入开始倒计时
func _on_mouse_entered_start_timer():
	timer.start()

#鼠标移出取消倒计时，并隐藏面板
func _on_mouse_exited_reset():
	timer.stop() #如果还没到0.5秒就移开了，这句会打断倒计时
	info_label.get_parent().hide() #确保面板消失

#倒计时结束显示面板
func _on_timer_timeout_show():
	var color_hex = data.color.to_html(false)
	info_label.text = "[color=#%s][b]%s[/b][/color]\n%s" % [color_hex, data.name, data.description]
	#显示面板
	info_label.get_parent().show()

func _on_exit():
	info_label.text = ""
	info_label.get_parent().hide() #隐藏面板

#拖拽逻辑
func _get_drag_data(at_position):
	if not Global.can_interact: return null
	
	get_tree().current_scene.play_sfx(sfx_take)
	
	#创建真正的预览图片
	var preview = TextureRect.new()
	preview.texture = texture
	preview.expand_mode = TextureRect.EXPAND_IGNORE_SIZE
	preview.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
	preview.size = Vector2(128, 128)
	preview.modulate.a = 1.0
	
	var preview_control = Control.new()
	preview_control.add_child(preview)
	preview.position = -preview.size / 2
	set_drag_preview(preview_control)
	
	self.modulate.a = 0.0
	
	return { 
		"type": "ingredient", 
		"id": data.id,
		"name": data.name,
		"color": data.color
	}

func _notification(what):
	if what == NOTIFICATION_DRAG_END:
		
		var tween = create_tween()
		tween.tween_property(self, "modulate:a", 1.0, 0.2)
